package com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.css.fxfzfxqh.base.dict.service.DictItemService;
import com.css.fxfzfxqh.base.dict.service.DictService;
import com.css.fxfzfxqh.base.dict.viewobjects.DictEntityVo;
import com.css.fxfzfxqh.base.response.RestResponse;
import com.css.fxfzfxqh.common.rest.JcsjRestManager;
import com.css.fxfzfxqh.constants.FxfzConstants;
import com.css.fxfzfxqh.constants.YNEnum;
import com.css.fxfzfxqh.modules.buildingIndividual.entity.BuildingIndividualEntity;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.exceptions.BizException;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.entity.CalculationTasks;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.entity.YSXMainTable;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.repository.CalculationTasksRepository;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.entity.BuildingVulnerability;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.entity.PCC;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.service.impl.CasualtiesDEServiceImpl1;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.vo.Grid13VO;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.entity.*;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.param.DEQueryParam;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.param.DETasksParam;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.param.ResistEarthquakesCalculationParam;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.param.AssessParam;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.repository.ResistEarthquakesDERepository;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.service.ResistEarthquakesDEService;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.vo.JcLd;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.vo.JcPga;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.vo.ResistEarthquakesPCCVO;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.vo.ResistEarthquakesXYVO;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.util.Tools;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.util.YSXUtil;
import com.css.fxfzfxqh.modules.seismicHazardData.entity.SettingInfluenceFliedEntity;
import com.css.fxfzfxqh.modules.seismicHazardData.repository.SeismicImpactFieldRepository;
import com.css.fxfzfxqh.modules.seismicHazardData.vo.InfluencefliedVo;
import com.css.fxfzfxqh.modules.singleIndexRiskZoning.model.entity.FxqhAssessEdQh;
import com.css.fxfzfxqh.modules.singleIndexRiskZoning.model.entity.FxqhAssessEdQhResult;
import com.css.fxfzfxqh.modules.util.Calculation;
import com.css.fxfzfxqh.modules.util.ExcelUtil;
import com.css.fxfzfxqh.modules.util.ResistEarthquakesEnum;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.util.YSXEntity;
import com.css.fxfzfxqh.modules.util.hypergraph.service.HypergraphService;
import com.css.fxfzfxqh.modules.util.repository.PccRepository;
import com.css.fxfzfxqh.modules.util.repository.YSXRepository;
import com.css.fxfzfxqh.util.*;
import com.css.fxfzfxqh.web.PlatformSessionContext;
import com.css.fxfzfxqh.zcpt.sys.entity.SUser;
import com.css.fxfzfxqh.zcpt.sys.service.SUserService;
import com.css.fxfzfxqh.zcpt.sys.service.SysAreaService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: zhangSongRui
 * @CreateTime: 2023/05/24
 * @Description: 抗震能力_确定评估
 */
@Slf4j
@Service
public class ResistEarthquakesDEServiceImpl implements ResistEarthquakesDEService {

    @Resource
    private ResistEarthquakesDERepository resistEarthquakesDERepository;
    @Resource
    private SysAreaService sysAreaService;
    @Resource
    DictService dictService;
    @Resource
    SUserService sUserService;
    @Resource
    PccRepository pccRepository;
    @Resource
    private YSXRepository ysxRepository;
    @Resource
    private HypergraphService hypergraphService;
    @Resource
    DictItemService dictItemService;
    @Resource
    private JcsjRestManager jcsjRestManager;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private Tools tools;
    @Resource
    private SeismicImpactFieldRepository seismicImpactFieldRepository;
    @Resource
    private CasualtiesDEServiceImpl1 casualtiesDEServiceImpl1;
    @Resource
    private CalculationTasksRepository calculationTasksRepository;
    @Resource
    private YSXUtil ySXUtil;


    /**
     * 新增抗震能力_确定评估
     *
     * @param param
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public void addAssess(ResistEarthquakesDE param) throws Exception {
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        param.setId(UUIDGenerator.getUUID());
        param.setCreateUser(sUser.getCreateUser());
        param.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        //创建人单位
        param.setCompany(sUser.getOrgName());
        param.setDelFlag(YNEnum.N.toString());
        //写入省市县
        if ("0".equals(param.getRadio2())) {
            setCCP(param);
        } else if ("2".equals(param.getRadio2())) {
            String areaRange = param.getAreaRange();
            areaRange = areaRange.replace("；", ";").replace("，", ",");
            //检查输入的范围的头一个经纬度和最后一个经纬度是否相同
            casualtiesDEServiceImpl1.check(areaRange);
            String geomText = casualtiesDEServiceImpl1.isGeomValid(areaRange);
            param.setCoordinateRange(geomText);
        }
        //如果为四个概率则先将值入库
        if (param.getSeismicInputMode().equals("1")) {
            if (null != param.getRadio2() & param.getRadio2().equals("1")) {
                try {
                    List<JcLd> ldData = jcsjRestManager.getLDList1(param.getCoordinateRange(), null).getData();
                    pccRepository.saveJcLd(ldData, param.getId());
                    List<JcPga> pgaData = jcsjRestManager.getPagList1(param.getCoordinateRange(), null).getData();
                    pccRepository.saveJcPag(pgaData, param.getId());
                } catch (BizException e) {
                    e.printStackTrace();
                }
            }
            //获得所有评估县
            List<PCC> pList = param.getList();
            for (PCC pcc : pList) {
                //将两种格式的数据,烈度格式,pga格式入库
                try {
                    List<JcLd> ldData = jcsjRestManager.getLDList(pcc.getPpName(), pcc.getCityName(), pcc.getName(), "").getData();
                    pccRepository.saveJcLd(ldData, param.getId());
                    List<JcPga> pgaData = jcsjRestManager.getPagList(pcc.getPpName(), pcc.getCityName(), pcc.getName(), "").getData();
                    pccRepository.saveJcPag(pgaData, param.getId());
                } catch (BizException e) {
                    e.printStackTrace();
                }
            }
        }
        resistEarthquakesDERepository.addAssess(param);
    }

    //写入省市县
    private void setCCP(ResistEarthquakesDE param) {
        List<PCC> pccList1 = new ArrayList<>();
        List<PCC> pccList = param.getList();
        if (pccList.size() != 0) {
            for (PCC pcc : pccList) {
                if (PlatformObjectUtils.isNotEmpty(pcc.getPpName())) {
                    if (PlatformObjectUtils.isEmpty(pcc.getCityName())) {
                        String childArea1 = sysAreaService.getChildAreaById(pcc.getPid());
                        List<PCCName> objects1 = JSON.parseArray(childArea1, PCCName.class);
                        for (PCCName pccName1 : objects1) {
                            String childArea2 = sysAreaService.getChildAreaById(pccName1.getId());
                            List<PCCName> objects2 = JSON.parseArray(childArea2, PCCName.class);
                            for (PCCName pccName2 : objects2) {
                                PCC pcc1 = new PCC();
                                pcc1.setAssessId(param.getId());
                                pcc1.setUuid(UUIDGenerator.getUUID());
                                pcc1.setPid(pcc.getPid());
                                pcc1.setPpName(pcc.getPpName());
                                pcc1.setCid(pccName1.getId());
                                pcc1.setCityName(pccName1.getName());
                                pcc1.setName(pccName2.getName());
                                pcc1.setId(pccName2.getId());
                                pccList1.add(pcc1);
                            }
                        }
                    } else {
                        if (PlatformObjectUtils.isEmpty(pcc.getName())) {
                            String childArea = sysAreaService.getChildAreaById(pcc.getCid());
                            List<PCCName> objects = JSON.parseArray(childArea, PCCName.class);
                            for (PCCName pccName : objects) {
                                PCC pcc1 = new PCC();
                                pcc1.setAssessId(param.getId());
                                pcc1.setUuid(UUIDGenerator.getUUID());
                                pcc1.setPid(pcc.getPid());
                                pcc1.setPpName(pcc.getPpName());
                                pcc1.setCid(pcc.getCid());
                                pcc1.setCityName(pcc.getCityName());
                                pcc1.setName(pccName.getName());
                                pcc1.setId(pccName.getId());
                                pccList1.add(pcc1);
                            }
                        } else {
                            pcc.setAssessId(param.getId());
                            pcc.setUuid(UUIDGenerator.getUUID());
                            pccList1.add(pcc);
                        }
                    }
                } else {
                    pcc.setAssessId(param.getId());
                    pcc.setUuid(UUIDGenerator.getUUID());
                    pccList1.add(pcc);
                }
            }
            pccRepository.batchSavePCC(pccList1);
        }
    }

    //根据id查询
    @Override
    public ResistEarthquakesDE findById(String id) {
        ResistEarthquakesDE byId = resistEarthquakesDERepository.findById(id);
        List<PCC> list = pccRepository.queryToponym(byId.getId());
        byId.setList(list);
        return byId;
    }

    @Override
    public List<EarthquakeAffectedField> getSeismicInfluence() {
        Map<String, Object> all = seismicImpactFieldRepository.getAll(1, 10);
        List<InfluencefliedVo> rows = (List<InfluencefliedVo>) all.get("rows");
        List<EarthquakeAffectedField> a = new ArrayList<>();
        for (InfluencefliedVo row : rows) {
            EarthquakeAffectedField obj = new EarthquakeAffectedField();
            obj.setFsiId(row.getVersionCode());
            a.add(obj);
        }
        return a;
    }

    //修改评估记录
    @Override
    @Transactional(rollbackFor=Exception.class)
    public void upDateAssess(ResistEarthquakesDE param) {
        param.setUpdateUser(PlatformSessionContext.getUserID());
        param.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        resistEarthquakesDERepository.upDateAssess(param);
    }

    //获取评估code
    @Override
    public String getCode(ResistEarthquakesDE param) {
        //抗震能力确定评估
        StringBuilder code = new StringBuilder("JZW-FW-QD");
        if (param.getHouseDataFlag().equals("0")) {
            //单体
            code.append("-DT");
        } else if (param.getHouseDataFlag().equals("1")) {
            //网格
            code.append("-WG");
        }
        if (StringUtils.isEmpty(param.getCoordinateRange())) {
            //如果经纬度范围为空
            code.append("-QH");
        } else {
            code.append("-QD");
        }
        if (param.getSeismicInputMode().equals("0")) {
            //烈度
            code.append("-LD");
        } else if (param.getSeismicInputMode().equals("1")) {
            //概率水准
            code.append("-GL");
        } else if (param.getSeismicInputMode().equals("2")) {
            //地震影响场
            code.append("-YX");
        }
        String[] split1 = code.toString().split("-");
        if (split1.length != 6) {
            return code.toString();
        }
        //查询最近一次code
        String oldCode = resistEarthquakesDERepository.queryLatest(code);
        if (StringUtils.isEmpty(oldCode)) {
            code.append("-0001");
        } else {
            String[] split = oldCode.split("-");
            code.append("-").append(getNext(split[6]));
        }
        return code.toString();
    }

    /****
     * 从哪里开始计数 比如startValue=2，则会从003,004,005等
     * @param startValue
     * @return
     */
    public String getNext(String startValue) {
        Integer i = Integer.valueOf(startValue);
        String format = String.format("%04d", i + 1);
        return format;
    }

    //分页查询
    @Override
    public Map<String, Object> getPage(int curPage, int pageSize, AssessParam param) {
        Map<String, Object> page = resistEarthquakesDERepository.getPage(curPage, pageSize, param);
        List<ResistEarthquakesDE> list = (List<ResistEarthquakesDE>) page.get("rows");
        for (ResistEarthquakesDE obj : list) {
            List<PCC> pccs = pccRepository.queryToponym(obj.getId());
            obj.setList(pccs);
        }
        page.put("rows", list);
        return page;
    }

    //经验评估与修正值
    @Override
    @Transactional(rollbackFor=Exception.class)
    public void updateCorrectionValue(ResistEarthquakesCalculation param) {
        resistEarthquakesDERepository.updateCorrectionValue(param);
    }

    /**
     * 省市县扩展 根据现有省市县拓展为所有县;
     *
     * @param list 评估记录
     * @return
     */
    private List<PCC> PCCExtend(List<PCC> list) {
        //省市县判断
        List<PCC> PCClist = new ArrayList<>();
        for (PCC pcc : list) {
            //如果有县id则跳过
            if (pcc.getId() != null) {
                PCClist.add(pcc);
                break;
            }
            //如果县id等于null,则判断是否有市id
            if (pcc.getCid() != null) {
                //有市id则根据市查询下面所有的县,并写入
                String jsonStr = sysAreaService.getChildAreaById(pcc.getCid());
                List<PCCName> objects = JSON.parseArray(jsonStr, PCCName.class);
                for (PCCName obj : objects) {
                    PCC pcc1 = new PCC();
                    //县id
                    pcc1.setId(obj.getId());
                    //县name
                    pcc1.setName(obj.getName());
                    //市id
                    pcc1.setCid(pcc.getCid());
                    //市name
                    pcc1.setName(pcc.getCityName());
                    //省id
                    pcc1.setName(pcc.getPid());
                    //省name
                    pcc1.setName(pcc.getPpName());
                    PCClist.add(pcc1);
                }
            } else {
                //如果没有市id则查询省id下面所有的市和县
                String jsonStr = sysAreaService.getChildAreaById(pcc.getPid());
                List<PCCName> cityList = JSON.parseArray(jsonStr, PCCName.class);
                for (PCCName obj : cityList) {
                    //县级
                    List<PCCName> cList = JSON.parseArray(sysAreaService.getChildAreaById(obj.getId()), PCCName.class);
                    for (PCCName pccName : cList) {
                        PCC pcc1 = new PCC();
                        //县id
                        pcc1.setId(pccName.getId());
                        //县name
                        pcc1.setName(pccName.getName());
                        //市id
                        pcc1.setCid(obj.getId());
                        //市name
                        pcc1.setName(obj.getName());
                        //省id
                        pcc1.setName(pcc.getPid());
                        //省name
                        pcc1.setName(pcc.getPpName());
                        PCClist.add(pcc1);
                    }
                }
            }
        }
        return PCClist;
    }

    //计算
    @Override
    @Transactional(rollbackFor=Exception.class)
    public RestResponse calculation(DETasksParam param) throws Exception {
        //初始时间
        long startTime = System.currentTimeMillis();
        //获取任务
        CalculationTasks tasks = calculationTasksRepository.findById(param.getTaskId());
        //根据地震输入方式判断
        if (param.getSeismicInputMode().equals("0")) {
            //烈度
            ldCalculation(tasks, getQuery(param.getSeismicInputMode(), tasks));
        }
        if (param.getSeismicInputMode().equals("1")) {
            //四个概率
            gl4Calculation(tasks, getQuery(param.getSeismicInputMode(), tasks));
        }
        if (param.getSeismicInputMode().equals("2")) {
            //地震影响场
            yxcCalculation(tasks, getQuery(param.getSeismicInputMode(), tasks));
        }
        //刷新指定超图工作空间数据源数据集
        boolean bool = hypergraphService.getWorkspaceReload("fxqh_resist_earthquakes_calculation_ed");
        if (bool) {
            log.info("刷新成功");
        } else {
            log.info("刷新失败");
        }
        //程序结束时间
        long endTime = System.currentTimeMillis();
        log.info("运行用时：" + (endTime - startTime) + "ms");
        return RestResponse.succeed("计算成功");
    }

    //将房屋单体转换成Grid13VO
    private Grid13VO get13VO(BuildingIndividualEntity obj) {
        Grid13VO grid13VO = new Grid13VO();
        //写入面积
        grid13VO.setTotalArea(Double.valueOf(obj.getArea()));
        //写入设防占比
        grid13VO.setSfIntensity(0.00);
        grid13VO.setSfIntensity6(0.00);
        grid13VO.setSfIntensity7(0.00);
        grid13VO.setSfIntensity8(0.00);
        grid13VO.setSfIntensity9(0.00);
        if (obj.equals("0")) {
            grid13VO.setSfIntensity(100.00);
        } else if (obj.equals("6")) {
            grid13VO.setSfIntensity6(100.00);
        } else if (obj.equals("7")) {
            grid13VO.setSfIntensity7(100.00);
        } else if (obj.equals("8")) {
            grid13VO.setSfIntensity8(100.00);
        } else if (obj.equals("9")) {
            grid13VO.setSfIntensity9(100.00);
        }
        return grid13VO;
    }

    //获取房屋单体结构类型,将传入的类型转成汉字
    private String getType(String type1, String type2) {
        //获取类型
        String type = dictService.getValueByDictCodeAndKey("jglxyj", type1);
        if (null != type2) {
            String code = null;
            if (type1.equals("1")) {
                //砌体结构
                code = "qtjgej";
            } else if (type1.equals("2")) {
                //钢筋混凝土
                code = "gjhntjgej";
            } else if (type1.equals("6")) {
                //工业厂房
                code = "gycfej";
            }
            String valueByDictCodeAndKey = dictService.getValueByDictCodeAndKey(code, type2);
            type = type + "-" + valueByDictCodeAndKey;
        }
        return type;
    }

    //地震输入方式为烈度的计算
    private void ldCalculation(CalculationTasks tasks, ArrayList<DEQueryParam> query) throws Exception{
        long startTime = System.currentTimeMillis();
        log.info("确定评估_结构破坏_烈度计算开始");
        //将所有的条件按顺序计算
        Map<String, Map<String, Double>> ysxMap = new HashMap<>();
        Map<String, List<Grid13VO>> gridMap = new HashMap<>();
        List<BuildingIndividualEntity> all = new ArrayList<>();
        List<DictEntityVo> dictItemByDictId = new ArrayList<>();
        if(tasks.getHouseDataFlag().equals("1")){
            //第一步根据版本号查询十三个房屋类型
            dictItemByDictId =  dictItemService.getDictItemByDictCode("jzwglgwlx");
        }
        List<Grid13VO> gridDataListAll = calculationTasksRepository.getLdDate(tasks.getId(), "0", "");;
        for (DEQueryParam deQueryParam : query) {
            //破坏程度
            String damageDegree = dictService.getValueByDictCodeAndKey("pgcd", deQueryParam.getDamageDegree());
            String condition = deQueryParam.getCondition();
            //
            if (tasks.getHouseDataFlag().equals("1")) {
                //循环所有省市县
                List<Calculation> calculationList = new ArrayList<>();
                for (DictEntityVo dictEntityVo : dictItemByDictId) {
                    String structureType = dictEntityVo.getDictItemCode();
                    //根据类型和格网名称,和省市县查询出对应的格网数据
//                    List<Grid13VO> gridDataList =  calculationTasksRepository.getLdDate(tasks.getId(), "", structureType);
                    List<Grid13VO> gridDataList = gridDataListAll.stream().filter(grid13VO -> structureType.equals(grid13VO.getDictionary())).collect(Collectors.toList());
//                    if(!gridMap.containsKey(structureType)){
//                        gridDataList =  calculationTasksRepository.getLdDate(tasks.getId(), "", structureType);
//                        gridMap.put(structureType,PlatformObjectUtils.isNotEmpty(gridDataList)?gridDataList:new ArrayList<>());
//                    }else{
//                        gridDataList = gridMap.get(structureType);
//                    }
                    for (Grid13VO obj : gridDataList) {
                        //如果没有格网id则直接跳过
                        if (null == obj.getExtends1()) {
                            continue;
                        }
                        //总面积当前坐标总面积
                        Double totalArea = obj.getTotalArea();
//                        Map<String, Double> ysxData = ySXUtil.getYSX(structureType, damageDegree, condition,
//                                obj.getProvince(), obj.getCity(), obj.getCounty(), tasks.getId());
                        //获取ysx
                        BigDecimal result = BigDecimal.ZERO;
                        if(totalArea>0){
                            Map<String, Double> ysxData = new HashMap<>();
                            if(!ysxMap.containsKey( obj.getProvince()+"_"+obj.getCity()+"_"+obj.getCounty()+"_"+structureType+"_"+condition+"_"+damageDegree)){
                                ysxData = ySXUtil.getYSX(structureType, damageDegree, condition,
                                        obj.getProvince(), obj.getCity(), obj.getCounty(), tasks.getId());
                                ysxMap.put(obj.getProvince()+"_"+obj.getCity()+"_"+obj.getCounty()+"_"+structureType+"_"+condition+"_"+damageDegree,ysxData);
                            }else{
                                ysxData = ysxMap.get(obj.getProvince()+"_"+obj.getCity()+"_"+obj.getCounty()+"_"+structureType+"_"+condition+"_"+damageDegree);
                            }

                            //无易损性数据则则跳过计算
                            if (ysxData.size() == 0) {
                                continue;
                            }
                            //计算
                            result = calculationByFortification(obj, condition, ysxData, totalArea);
                        }

                        //存入数据,这十三个结构类型共同标记为字段geom;
                        Calculation calculation = getCalculation(obj, deQueryParam, structureType, result, totalArea, "0");
                        calculationList.add(calculation);
                    }
                }
                //计算最终结果并入库
                List<ResistEarthquakesCalculation> conditionValue = getConditionValue(deQueryParam, calculationList, tasks, "0");

                if (conditionValue.size() != 0) {
                    log.info("开始入库");
                    //删除改评估记录该条件下旧的计算值
                    resistEarthquakesDERepository.deleteCalculationByQuery(conditionValue.get(0));
                    resistEarthquakesDERepository.batchCalculation(conditionValue);
                    log.info("入库结束");
                }

            } else {
                //单体
                ArrayList<ResistEarthquakesCalculation> conditionValue = new ArrayList<>();
                List<BuildingIndividualEntity> result = calculationTasksRepository.getLdDtDate(tasks.getId(), "0");

                if (result.size() == 0) {
                    throw new RuntimeException("计算未完成，没有获取到房屋单体数据");
                }
                for (BuildingIndividualEntity obj : result) {
                    //将房屋单体转换成13VO
                    Grid13VO grid13VO = get13VO(obj);
                    //总面积当前坐标总面积
                    Double totalArea = Double.valueOf(obj.getArea());
                    //获取ysx
                    //Map<String, Double> ysxData = ySXUtil.getYSX(obj.getStructureType1(), obj.getStructureType2(), damageDegree, condition, obj.getProvince(), obj.getCity(), obj.getCounty(), tasks.getId());
                    Map<String, Double> ysxData = new HashMap<>();
                    if(!ysxMap.containsKey( obj.getProvince()+"_"+obj.getCity()+"_"+obj.getCounty()+"_"+obj.getStructureType1()+"_"+obj.getStructureType2()+"_"+condition+"_"+damageDegree)){
                        ysxData = ySXUtil.getYSX(obj.getStructureType1(), obj.getStructureType2(), damageDegree, condition,
                                obj.getProvince(), obj.getCity(), obj.getCounty(), tasks.getId());
                        ysxMap.put(obj.getProvince()+"_"+obj.getCity()+"_"+obj.getCounty()+"_"+obj.getStructureType1()+"_"+obj.getStructureType2()+"_"+condition+"_"+damageDegree,ysxData);
                    }else{
                        ysxData = ysxMap.get(obj.getProvince()+"_"+obj.getCity()+"_"+obj.getCounty()+"_"+obj.getStructureType1()+"_"+obj.getStructureType2()+"_"+condition+"_"+damageDegree);
                    }
                    //无易损性数据则则跳过计算
                    if (ysxData.size() == 0) {
                        continue;
                    }
                    //计算
                    BigDecimal mathResult = calculationByFortification(grid13VO, condition, ysxData, totalArea);
                    //抗震能力
                    BigDecimal value = mathResult.divide(BigDecimal.valueOf(totalArea), 8, BigDecimal.ROUND_DOWN);
                    //装入list
                    ResistEarthquakesCalculation calculation = getMonomerObj(obj, deQueryParam, tasks, "0", value, "");
                    conditionValue.add(calculation);
                }
                log.info("开始入库");
                if (conditionValue.size() != 0) {
                    //删除改评估记录该条件下旧的计算值
                    resistEarthquakesDERepository.deleteCalculationByQuery(conditionValue.get(0));
                    resistEarthquakesDERepository.batchCalculation(conditionValue);
                }
                log.info("入库结束");
            }
        }
        //更新建筑物任务状态为烈度计算完成
        calculationTasksRepository.updateLdProgress(tasks.getId(), "评估", "结构破坏");
        long endTime = System.currentTimeMillis();
        log.info("确定评估_结构破坏_烈度计算结束,用时:" + (endTime - startTime) + "ms");
    }

    //4个概率计算
    private void gl4Calculation(CalculationTasks tasks, ArrayList<DEQueryParam> query) throws Exception{
        long startTime = System.currentTimeMillis();
        log.info("确定评估_结构破坏_4个概率计算开始");
        //将所有的条件按顺序计算
        List<DictEntityVo> dictItemByDictId = new ArrayList<>();
        Map<String, List<Grid13VO>> collect = new HashMap<>();
        List<BuildingIndividualEntity> all = new ArrayList<>();
        if (tasks.getHouseDataFlag().equals("1")) {
            //第一步根据版本号查询十三个房屋类型
            dictItemByDictId = dictItemService.getDictItemByDictCode("jzwglgwlx");
            //一次获取到所有的网格数据;
            List<Grid13VO> gridDataListAll = calculationTasksRepository.getLdDate(tasks.getId(), "1", "");
            if(PlatformObjectUtils.isNotEmpty(gridDataListAll)){
                //烈度转换
                pgaTransform(gridDataListAll, tasks.getLdPga());
                //通过类型分组，得到map
                collect = gridDataListAll.stream().collect(Collectors.groupingBy(entity -> entity.getDictionary()));
            }else{
                throw new RuntimeException("评估未完成，无法获取房屋格网数据");
            }
        }else{
            all = calculationTasksRepository.getLdDtDate(tasks.getId(), "0");
            if(PlatformObjectUtils.isEmpty(all) || all.size()==0){
                throw new RuntimeException("评估未完成，无法获取房屋单体数据");
            }
        }
        Map<String, Map<String, List<YSXMainTable>>> stringListMap = new HashMap<>();
        Map<String,Map<String, Double>> ysxMap = new HashMap<>();
        for (DEQueryParam deQueryParam : query) {
            //破坏程度
            String damageDegree = dictService.getValueByDictCodeAndKey("pgcd", deQueryParam.getDamageDegree());
            String conditionGL = deQueryParam.getCondition();
            //判断是否为省市县
            if (tasks.getHouseDataFlag().equals("1")) {
                List<Calculation> calculationList = new ArrayList<>();
                for (DictEntityVo dictEntityVo : dictItemByDictId) {
                    String structureType = dictEntityVo.getDictItemCode();
                    //根据类型和格网名称,和省市县查询出对应的格网数据
                    List<Grid13VO> gridDataList = collect.get(structureType);
                    if(PlatformObjectUtils.isNotEmpty(gridDataList)){
                        //List<Grid13VO> gridDataList = calculationTasksRepository.getLdDate(tasks.getId(), "1", structureType);
                        //去重
                        //gridDataList = FilterDuplicateData(gridDataList);
                        for (Grid13VO obj : gridDataList) {
                            //如果没有格网id则直接跳过
                            if (null == obj.getExtends1()) {
                                continue;
                            }
                            //当前obj再当前概率下的烈度
                            String condition = null;
                            //如果是四个概率则将烈度赋值为查询出来的烈度
                            if (conditionGL.equals("sgglsz3")) {
                                condition = obj.getYear50ProExceedance002();
                            } else if (conditionGL.equals("sgglsz2")) {
                                condition = obj.getYear50ProExceedance010();
                            } else if (conditionGL.equals("sgglsz1")) {
                                condition = obj.getYear50ProExceedance063();
                            } else if (conditionGL.equals("sgglsz4")) {
                                condition = obj.getYear100ProExceedance001();
                            }
                            if (PlatformObjectUtils.isEmpty(condition)) {
                                continue;
                            }
                            //总面积当前坐标总面积
                            Double totalArea = obj.getTotalArea();
                            //获取ysx
                            Map<String, List<YSXMainTable>> stringListMap1 = new HashMap<>();
                            if (!stringListMap.containsKey(obj.getProvince() + "_" + obj.getCity() + "_" + obj.getCounty())) {
                                stringListMap1 = ySXUtil.ysxEncapsulationNew2(tasks.getId(), obj.getProvince(), obj.getCity(), obj.getCounty());
                                stringListMap.put(obj.getProvince() + "_" + obj.getCity() + "_" + obj.getCounty(), stringListMap1);
                            }else{
                                stringListMap1  = stringListMap.get(obj.getProvince() + "_" + obj.getCity() + "_" + obj.getCounty());
                            }
                        /*Map<String, Double> ysxData = ySXUtil.getYSX(structureType, damageDegree, condition,
                                obj.getProvince(), obj.getCity(), obj.getCounty(), tasks.getId());*/
                            //无易损性数据则则跳过计算
                            if (PlatformObjectUtils.isEmpty(stringListMap)) {
                                continue;
                            }
                        /*if (ysxData.size() == 0) {
                            continue;
                        }*/
                            //结构类型_毁坏程度_烈度
                            if (PlatformObjectUtils.isEmpty(stringListMap1)) {
                                continue;
                            }
                            String structureTypeName = ySXUtil.getStructureType(structureType);
                            if(!structureTypeName.contains("-")){
                                structureTypeName = structureTypeName+"-"+structureTypeName;
                            }
                            //conditionName 取值是5度-10度
                            String conditionName = ySXUtil.ldConversion(condition);
                            List<YSXMainTable> ysxMainTables = stringListMap1.get(structureTypeName + damageDegree + conditionName);
                            if (PlatformObjectUtils.isEmpty(ysxMainTables)) {
                                throw new RuntimeException("评估未完成，无法获取"+structureTypeName+"烈度为"+conditionName+"的易损性数据");
                            }
                            Map<String, Double> ysxData1 = new HashMap<>();
                            for (YSXMainTable entity : ysxMainTables) {
                                ysxData1.put(entity.getFortify(), Double.valueOf(entity.getRate().replace("%", "")));
                            }
                            //计算
                            BigDecimal result = calculationByFortification(obj, condition, ysxData1, totalArea);
                            DEQueryParam deQueryParam2 = new DEQueryParam();
                            deQueryParam2.setDamageDegree(damageDegree);
                            deQueryParam2.setCondition(condition);
                            //存入数据,这十三个结构类型共同标记为字段geom;
                            Calculation calculation = getCalculation(obj, deQueryParam2, structureType, result, totalArea, "1");
                            calculationList.add(calculation);
                        }
                    }
                }
                if(calculationList.size()>0){
                    //计算最终结果并入库
                    List<ResistEarthquakesCalculation> conditionValue = getConditionValue(deQueryParam, calculationList, tasks, "1");
                    log.info("开始入库");
                    if (conditionValue.size() != 0) {
                        //删除改评估记录该条件下旧的计算值
                        resistEarthquakesDERepository.deleteCalculationByQuery(conditionValue.get(0));
                        resistEarthquakesDERepository.batchCalculation(conditionValue);
                    }
                    log.info("入库结束");
                }
            } else {
                ArrayList<ResistEarthquakesCalculation> conditionValue = new ArrayList<>();
                //List<BuildingIndividualEntity> all = calculationTasksRepository.getLdDtDate(tasks.getId(), "0");
                pgaTransform2(all, tasks.getLdPga());
                //如果有数据则去重
                all = FilterDuplicateData2(all);
                for (BuildingIndividualEntity obj : all) {
                    //当前obj再当前概率下的烈度
                    String condition = null;
                    //如果是四个概率则将烈度赋值为查询出来的烈度
                    if (conditionGL.equals("sgglsz3")) {
                        condition = obj.getYear50ProExceedance002();
                    } else if (conditionGL.equals("sgglsz2")) {
                        condition = obj.getYear50ProExceedance010();
                    } else if (conditionGL.equals("sgglsz1")) {
                        condition = obj.getYear50ProExceedance063();
                    } else if (conditionGL.equals("sgglsz4")) {
                        condition = obj.getYear100ProExceedance001();
                    }
                    //将房屋单体转换成13VO
                    Grid13VO grid13VO = get13VO(obj);
                    //总面积当前坐标总面积
                    Double totalArea = Double.valueOf(obj.getArea());
                    //获取ysx
                    Map<String, Double> ysxData = new HashMap<>();
                    if(!ysxMap.containsKey(obj.getProvince()+"_"+obj.getCity()+"_"+obj.getCounty()+"_"+obj.getStructureType1()+"_"+ obj.getStructureType2()+"_"+damageDegree+"_"+condition)){
                        ysxData = ySXUtil.getYSX(obj.getStructureType1(), obj.getStructureType2(), damageDegree, condition, obj.getProvince(), obj.getCity(), obj.getCounty(), tasks.getId());
                        ysxMap.put(obj.getProvince()+"_"+obj.getCity()+"_"+obj.getCounty()+"_"+obj.getStructureType1()+"_"+ obj.getStructureType2()+"_"+damageDegree+"_"+condition,ysxData);
                    }else{
                        ysxData = ysxMap.get(obj.getProvince()+"_"+obj.getCity()+"_"+obj.getCounty()+"_"+obj.getStructureType1()+"_"+ obj.getStructureType2()+"_"+damageDegree+"_"+condition);
                    }
                    //无易损性数据则则跳过计算
                    if (ysxData.size() == 0) {
                        continue;
                    }
                    //计算
                    BigDecimal result = calculationByFortification(grid13VO, condition, ysxData, totalArea);
                    //抗震能力
                    BigDecimal value = result.divide(BigDecimal.valueOf(totalArea), 4, BigDecimal.ROUND_DOWN);
                    //装入list
                    ResistEarthquakesCalculation calculation = getMonomerObj(obj, deQueryParam, tasks, "1", value, condition);
                    conditionValue.add(calculation);
                }
                log.info("开始入库");
                if (conditionValue.size() != 0) {
                    //删除改评估记录该条件下旧的计算值
                    resistEarthquakesDERepository.deleteCalculationByQuery(conditionValue.get(0));
                    resistEarthquakesDERepository.batchCalculation(conditionValue);
                }
                log.info("入库结束");
            }

        }
        //更新建筑物任务状态为烈度计算完成
        calculationTasksRepository.updateFourProbabilisticProgress(tasks.getId(), "评估", "结构破坏");
        long endTime = System.currentTimeMillis();
        log.info("确定评估_结构破坏_4个概率计算结束,用时:" + (endTime - startTime) + "ms");
    }


    //地震影响场计算
    private void yxcCalculation(CalculationTasks tasks, ArrayList<DEQueryParam> query) {
        long startTime = System.currentTimeMillis();
        log.info("确定评估_结构破坏_地震影响场计算开始");
        //将所有的条件按顺序计算
        //第一步根据版本号查询十三个房屋类型
        List<DictEntityVo> dictItemByDictId = new ArrayList<>();
        Map<String,List<Grid13VO>> gridMap = new HashMap<>();
        List<BuildingIndividualEntity> all = new ArrayList<>();
        if (tasks.getHouseDataFlag().equals("1")) {
            dictItemByDictId =  dictItemService.getDictItemByDictCode("jzwglgwlx");
        }else{
            all = calculationTasksRepository.getLdDtDate(tasks.getId(), "0");
        }
        Map<String,Map<String, Double>> ysxMap = new HashMap<>();
        for (DEQueryParam deQueryParam : query) {
            //破坏程度
            String damageDegree = dictService.getValueByDictCodeAndKey("pgcd", deQueryParam.getDamageDegree());
            //判断是否为省市县
            if (tasks.getHouseDataFlag().equals("1")) {
                List<Calculation> calculationList = new ArrayList<>();
                for (DictEntityVo dictEntityVo : dictItemByDictId) {
                    String structureType = dictEntityVo.getDictItemCode();
                    //根据类型和格网名称,和省市县查询出对应的格网数据
                    List<Grid13VO>  gridDataList = new ArrayList<>();
                    if(!gridMap.containsKey(structureType+"_"+ deQueryParam.getCondition())){
                        gridDataList = calculationTasksRepository.getYXCDate(tasks.getId(), "2", structureType, deQueryParam.getCondition());
                        gridMap.put(structureType+"_"+ deQueryParam.getCondition(),gridDataList);
                    }else{
                        gridDataList = gridMap.get(structureType+"_"+ deQueryParam.getCondition());
                    }

                    for (Grid13VO obj : gridDataList) {
                        //如果没有格网id则直接跳过
                        if (null == obj.getExtends1()) {
                            continue;
                        }
                        //总面积当前坐标总面积
                        Double totalArea = obj.getTotalArea();
                        Map<String, Double> ysxData = new HashMap<>();
                        if(!ysxMap.containsKey( obj.getProvince()+"_"+obj.getCity()+"_"+obj.getCounty()+"_"+structureType+"_"+obj.getDzIntensity()+"_"+damageDegree)){
                            ysxData = ySXUtil.getYSX(structureType, damageDegree, obj.getDzIntensity(), obj.getProvince(), obj.getCity(), obj.getCounty(), tasks.getId());;
                            ysxMap.put(obj.getProvince()+"_"+obj.getCity()+"_"+obj.getCounty()+"_"+structureType+"_"+obj.getDzIntensity()+"_"+damageDegree,ysxData);
                        }else{
                            ysxData = ysxMap.get(obj.getProvince()+"_"+obj.getCity()+"_"+obj.getCounty()+"_"+structureType+"_"+obj.getDzIntensity()+"_"+damageDegree);
                        }

                        //无易损性数据则则跳过计算
                        if (ysxData.size() == 0) {
                            continue;
                        }
                        //计算
                        BigDecimal result = calculationByFortification(obj, obj.getDzIntensity(), ysxData, totalArea);
                        //存入数据,这十三个结构类型共同标记为字段geom;
                        Calculation calculation = getCalculation(obj, deQueryParam, structureType, result, totalArea, "2");
                        calculationList.add(calculation);
                    }
                }
                //计算最终结果并入库
                List<ResistEarthquakesCalculation> conditionValue = getConditionValue(deQueryParam, calculationList, tasks, "2");
                log.info("开始入库");
                if (conditionValue.size() != 0) {
                    //删除改评估记录该条件下旧的计算值
                    resistEarthquakesDERepository.deleteCalculationByQuery(conditionValue.get(0));
                    resistEarthquakesDERepository.batchCalculation(conditionValue);
                }
                log.info("入库结束");
            } else {
                ArrayList<ResistEarthquakesCalculation> conditionValue = new ArrayList<>();
                if (all.size() == 0) {
                    log.info("没有数据");
                    continue;
                }
                for (BuildingIndividualEntity obj : all) {
                    //将房屋单体转换成13VO
                    Grid13VO grid13VO = get13VO(obj);
                    //总面积当前坐标总面积
                    Double totalArea = Double.valueOf(obj.getArea());
                    //获取ysx
                    Map<String, Double> ysxData = new HashMap<>();
                    if(!ysxMap.containsKey( obj.getProvince()+"_"+obj.getCity()+"_"+obj.getCounty()+"_"+obj.getStructureType1()+"_"+obj.getStructureType2()+"_"+obj.getDzIntensity()+"_"+damageDegree)){
                        ysxData = ySXUtil.getYSX(obj.getStructureType1()+"_"+obj.getStructureType2(), damageDegree, obj.getDzIntensity(), obj.getProvince(), obj.getCity(), obj.getCounty(), tasks.getId());;
                        ysxMap.put(obj.getProvince()+"_"+obj.getCity()+"_"+obj.getCounty()+"_"+obj.getStructureType1()+"_"+obj.getStructureType2()+"_"+obj.getDzIntensity()+"_"+damageDegree,ysxData);
                    }else{
                        ysxData = ysxMap.get(obj.getProvince()+"_"+obj.getCity()+"_"+obj.getCounty()+"_"+obj.getStructureType1()+"_"+obj.getStructureType2()+"_"+obj.getDzIntensity()+"_"+damageDegree);
                    }
                    //Map<String, Double> ysxData = ySXUtil.getYSX(obj.getStructureType1(), obj.getStructureType2(), damageDegree, obj.getDzIntensity(), obj.getProvince(), obj.getCity(), obj.getCounty(), tasks.getId());
                    //无易损性数据则则跳过计算
                    if (ysxData.size() == 0) {
                        continue;
                    }
                    //计算
                    BigDecimal result = calculationByFortification(grid13VO, obj.getDzIntensity(), ysxData, totalArea);
                    //抗震能力
                    BigDecimal value = result.divide(BigDecimal.valueOf(totalArea), 4, BigDecimal.ROUND_DOWN);
                    //装入list
                    ResistEarthquakesCalculation calculation = getMonomerObj(obj, deQueryParam, tasks, "2", value, "");
                    conditionValue.add(calculation);
                }
                log.info("开始入库");
                if (conditionValue.size() != 0) {
                    //删除改评估记录该条件下旧的计算值
                    resistEarthquakesDERepository.deleteCalculationByQuery(conditionValue.get(0));
                    resistEarthquakesDERepository.batchCalculation(conditionValue);
                }
                log.info("入库结束");
            }
        }
        //获取影响场烈度过度格网并删除烈度小的
        delectGW(tasks);
        //更新地震影响场计算进度
        calculationTasksRepository.updateStructuralFieldProgress(tasks.getId(), "评估", "结构破坏");
        long endTime = System.currentTimeMillis();
        log.info("确定评估_结构破坏_地震影响场计算结束,用时:" + (endTime - startTime) + "ms");
    }

    //根据地震输入方式获取条件
    private ArrayList<DEQueryParam> getQuery(String seismicInputMode, CalculationTasks tasks) {
        //写入条件
        ArrayList<DEQueryParam> listParam = new ArrayList<>();
        if (seismicInputMode.equals("0")) {
            for (int i = 1; i < 6; i++) {
                for (int j = 1; j < 6; j++) {
                    DEQueryParam obj = new DEQueryParam();
                    //写入条件
                    obj.setCondition("ld" + i);
                    //破坏状态
                    obj.setDamageDegree("pgcd" + j);
                    listParam.add(obj);
                }
            }
        }
        if (seismicInputMode.equals("1")) {
            for (int i = 1; i < 5; i++) {
                //四个概率
                for (int j = 1; j < 6; j++) {
                    DEQueryParam obj = new DEQueryParam();
                    //写入条件
                    obj.setCondition("sgglsz" + i);
                    //破坏状态
                    obj.setDamageDegree("pgcd" + j);
                    listParam.add(obj);
                }
            }
        }
        if (seismicInputMode.equals("2")) {
            //地震影响场
            List<SettingInfluenceFliedEntity> seismicInfluence = seismicImpactFieldRepository.getInfluencefliedById(tasks.getInfluenceFieldVersion());
            for (SettingInfluenceFliedEntity earthquakeAffectedField : seismicInfluence) {
                for (int i = 1; i < 6; i++) {
                    DEQueryParam obj = new DEQueryParam();
                    //写入条件
                    obj.setCondition(earthquakeAffectedField.getId());
                    //破坏状态
                    obj.setDamageDegree("pgcd" + i);
                    listParam.add(obj);
                }
            }
        }
        return listParam;
    }

    private void delectGW(CalculationTasks tasks) {
        //地震影响场
        List<SettingInfluenceFliedEntity> seismicInfluence = seismicImpactFieldRepository.getInfluencefliedById(tasks.getInfluenceFieldVersion());
        HashMap<String, Integer> map1 = new HashMap<>();
        for (SettingInfluenceFliedEntity earthquakeAffectedField : seismicInfluence) {
            map1.put(earthquakeAffectedField.getId(), Integer.valueOf(earthquakeAffectedField.getDzIntensity()));
        }
        List<ResistEarthquakesCalculation> list = resistEarthquakesDERepository.findByAssessId(tasks.getId());
        List<List<ResistEarthquakesCalculation>> result = new ArrayList<>();
        Map<String, List<ResistEarthquakesCalculation>> map = new HashMap<>();
        ArrayList<String> idList = new ArrayList<>();
        //将获得的所有数据进行归并,从而获得每个一样的geom下的所有计算值,并进行计算
        for (ResistEarthquakesCalculation calculation : list) {
            String extends1 = calculation.getExtends1();
            List<ResistEarthquakesCalculation> newList;
            if (map.containsKey(extends1)) {
                newList = map.get(extends1);
            } else {
                newList = new ArrayList<>();
            }
            newList.add(calculation);
            map.put(extends1, newList);
        }
        //写入list计算用
        for (Map.Entry<String, List<ResistEarthquakesCalculation>> entry : map.entrySet()) {
            result.add(entry.getValue());
        }
        for (List<ResistEarthquakesCalculation> resistEarthquakesCalculations : result) {
            //循环对比一个空间数据下的条件是否都一样,如果不一样则将烈度小的id取出来
            for (int i = 0; i < resistEarthquakesCalculations.size(); i++) {
                ResistEarthquakesCalculation calculationI = resistEarthquakesCalculations.get(i);
                //最后一位结束循环
                if (i + 1 >= resistEarthquakesCalculations.size()) {
                    break;
                }
                for (int j = i + 1; j < resistEarthquakesCalculations.size(); j++) {
                    ResistEarthquakesCalculation calculationJ = resistEarthquakesCalculations.get(j);
                    //如果条件字段不相等则记录小的那个
                    if (!calculationJ.getCondition().equals(calculationI.getCondition())) {
                        //判断那个小
                        Integer getJ = map1.get(calculationJ.getCondition());
                        Integer getI = map1.get(calculationI.getCondition());
                        //获取烈度小的那个计算的id
                        if (PlatformObjectUtils.isNotEmpty(getJ) && PlatformObjectUtils.isNotEmpty(getI) && getJ > getI) {
                            idList.add(calculationI.getId());
                        } else if (PlatformObjectUtils.isNotEmpty(getJ) && PlatformObjectUtils.isNotEmpty(getI) && getJ < getI) {
                            idList.add(calculationJ.getId());
                        }
                    }
                }
            }
        }
        //将所有格网重复并且烈度小的影响场计算数据删除
        if (idList.size() != 0) {
            resistEarthquakesDERepository.deleteSmallField(idList);
        }
    }

    /**
     * 将影响场烈度转化为字典值
     *
     * @param dzIntensity 地震影响场的地震影响场地震烈度
     * @return 对应字典值
     */
    private String convertDzIntensity(String dzIntensity) {
        if (dzIntensity.equals("6")) {
            return "ld1";
        }
        if (dzIntensity.equals("7")) {
            return "ld2";
        }
        if (dzIntensity.equals("8")) {
            return "ld3";
        }
        if (dzIntensity.equals("9")) {
            return "ld4";
        }
        if (dzIntensity.equals("10")) {
            return "ld5";
        }
        return null;
    }

    //计算设防烈度 ysxData》省_市_县_结构类型1_结构类型2_地震烈度_破坏程度下的设防烈度和对应的易损性的值
    private BigDecimal calculationByFortification(Grid13VO obj, String condition, Map<String, Double> ysxData, Double totalArea) {
        //当前结构类型的计算值
        BigDecimal result = BigDecimal.ZERO;
        //设防烈度为0的标记,如果为5则说明所有设防烈度都为0
        int fang = 0;
        //计算出各个设防的值
        //如果不设防不等于0
        if (obj.getSfIntensity() > 0.0) {
            if (null != condition) {
                //根据条件获取易损性值
                Double ysxValue = ysxData.get("未设防");
                //获得计算好的值
                BigDecimal area = getArea(obj.getSfIntensity(), totalArea, ysxValue);
                //所有防震等级都相加结果相加
                result = result.add(area);
            }
        } else {
            fang = fang + 1;
        }
        //如果现设防烈度_6度房屋面积占比不等于0
        if (obj.getSfIntensity6() > 0.0) {
            if (null != condition) {
                Double ysxValue = ysxData.get("6度");
                BigDecimal area = getArea(obj.getSfIntensity6(), totalArea, ysxValue);
                result = result.add(area);
            }
        } else {
            fang = fang + 1;
        }
        //如果现设防烈度_7度房屋面积占比不等于0
        if (obj.getSfIntensity7() > 0.0) {
            if (null != condition) {
                Double ysxValue = ysxData.get("7度");
                BigDecimal area = getArea(obj.getSfIntensity7(), totalArea, ysxValue);
                result = result.add(area);
            }
        } else {
            fang = fang + 1;
        }
        //如果现设防烈度_8度房屋面积占比不等于0
        if (obj.getSfIntensity8() > 0.0) {
            if (null != condition) {
                Double ysxValue = ysxData.get("8度");
                BigDecimal area = getArea(obj.getSfIntensity8(), totalArea, ysxValue);
                result = result.add(area);
            }
        } else {
            fang = fang + 1;
        }
        //如果现设防烈度_9度房屋面积占比不等于0
        if (obj.getSfIntensity9() > 0.0 ) {
            if (null != condition) {
                Double ysxValue = ysxData.get("9度");
                BigDecimal area = getArea(obj.getSfIntensity9(), totalArea, ysxValue);
                result = result.add(area);
            }
        } else {
            fang = fang + 1;
        }
        //如果没有一个设防结构有值则默认为未设防100%,并且在有总面积的时候计算
        if (fang == 5 & totalArea > 0.0) {
            if (null != condition) {
                //根据条件获取易损性值
                Double ysxValue = ysxData.get("未设防");
                //获得计算好的值
                BigDecimal area = getArea(Double.valueOf("100"), totalArea, ysxValue);
                //所有防震等级都相加结果相加
                result = result.add(area);
            }
        }
        return result;
    }

    //房屋单体四个概率过滤重复数据
    private List<BuildingIndividualEntity> FilterDuplicateData2(List<BuildingIndividualEntity> gridDataList) {
        ArrayList<BuildingIndividualEntity> list = new ArrayList<>();
        List<List<BuildingIndividualEntity>> result = new ArrayList<>();
        Map<String, List<BuildingIndividualEntity>> map = new HashMap<>();
        //将获得的所有数据进行归并,从而获得每个一样的geom下的所有计算值,并进行计算
        for (BuildingIndividualEntity obj : gridDataList) {
            String id = obj.getId();
            List<BuildingIndividualEntity> newList;
            newList = map.get(id);
            if (map.containsKey(id)) {
            } else {
                newList = new ArrayList<>();
            }
            newList.add(obj);
            map.put(id, newList);
        }
        //写入list计算用
        for (Map.Entry<String, List<BuildingIndividualEntity>> entry : map.entrySet()) {
            result.add(entry.getValue());
        }
        for (List<BuildingIndividualEntity> grid13VOS : result) {
            list.add(grid13VOS.get(0));
        }
        return list;
    }

    //过滤重复数据
    private List<Grid13VO> FilterDuplicateData(List<Grid13VO> gridDataList) {
        ArrayList<Grid13VO> list = new ArrayList<>();
        List<List<Grid13VO>> result = new ArrayList<>();
        Map<String, List<Grid13VO>> map = new HashMap<>();
        //将获得的所有数据进行归并,从而获得每个一样的geom下的所有计算值,并进行计算
        for (Grid13VO obj : gridDataList) {
            String extends1 = obj.getExtends1();
            List<Grid13VO> newList;
            newList = map.get(extends1);
            if (map.containsKey(extends1)) {
            } else {
                newList = new ArrayList<>();
            }
            newList.add(obj);
            map.put(extends1, newList);
        }
        //写入list计算用
        for (Map.Entry<String, List<Grid13VO>> entry : map.entrySet()) {
            result.add(entry.getValue());
        }
        for (List<Grid13VO> grid13VOS : result) {
            list.add(grid13VOS.get(0));
        }
        return list;
    }

    //pga转化
    private void pgaTransform2(List<BuildingIndividualEntity> pga, String fang) {
        for (BuildingIndividualEntity grid13VO : pga) {
            //烈度6
            if (null != grid13VO.getYear50ProExceedance002()) {
                if (fang.equals("1")) {
                    grid13VO.setYear50ProExceedance002(sectionPag(Double.valueOf(grid13VO.getYear50ProExceedance002())));
                } else {
                    grid13VO.setYear50ProExceedance002(sectionLD(grid13VO.getYear50ProExceedance002()));
                }
            }
            //50年内超越概率10%
            if (null != grid13VO.getYear50ProExceedance010()) {
                if (fang.equals("1")) {
                    grid13VO.setYear50ProExceedance010(sectionPag(Double.valueOf(grid13VO.getYear50ProExceedance010())));
                } else {
                    grid13VO.setYear50ProExceedance010(sectionLD(grid13VO.getYear50ProExceedance010()));
                }
            }
            //50年内超越概率63%
            if (null != grid13VO.getYear50ProExceedance063()) {
                if (fang.equals("1")) {
                    grid13VO.setYear50ProExceedance063(sectionPag(Double.valueOf(grid13VO.getYear50ProExceedance063())));
                } else {
                    grid13VO.setYear50ProExceedance063(sectionLD(grid13VO.getYear50ProExceedance063()));
                }
            }
            //100年内超越概率1%
            if (null != grid13VO.getYear100ProExceedance001()) {
                if (fang.equals("1")) {
                    grid13VO.setYear100ProExceedance001(sectionPag(Double.valueOf(grid13VO.getYear100ProExceedance001())));
                } else {
                    grid13VO.setYear100ProExceedance001(sectionLD(grid13VO.getYear100ProExceedance001()));
                }
            }
        }
    }

    //pga转化
    private void pgaTransform(List<Grid13VO> pga, String fang) {
        for (Grid13VO grid13VO : pga) {
            //烈度6
            if (null != grid13VO.getYear50ProExceedance002()) {
                if (fang.equals("1")) {
                    grid13VO.setYear50ProExceedance002(sectionPag(Double.valueOf(grid13VO.getYear50ProExceedance002())));
                } else {
                    grid13VO.setYear50ProExceedance002(sectionLD(grid13VO.getYear50ProExceedance002()));
                }
            }
            //50年内超越概率10%
            if (null != grid13VO.getYear50ProExceedance010()) {
                if (fang.equals("1")) {
                    grid13VO.setYear50ProExceedance010(sectionPag(Double.valueOf(grid13VO.getYear50ProExceedance010())));
                } else {
                    grid13VO.setYear50ProExceedance010(sectionLD(grid13VO.getYear50ProExceedance010()));
                }
            }
            //50年内超越概率63%
            if (null != grid13VO.getYear50ProExceedance063()) {
                if (fang.equals("1")) {
                    grid13VO.setYear50ProExceedance063(sectionPag(Double.valueOf(grid13VO.getYear50ProExceedance063())));
                } else {
                    grid13VO.setYear50ProExceedance063(sectionLD(grid13VO.getYear50ProExceedance063()));
                }
            }
            //100年内超越概率1%
            if (null != grid13VO.getYear100ProExceedance001()) {
                if (fang.equals("1")) {
                    grid13VO.setYear100ProExceedance001(sectionPag(Double.valueOf(grid13VO.getYear100ProExceedance001())));
                } else {
                    grid13VO.setYear100ProExceedance001(sectionLD(grid13VO.getYear100ProExceedance001()));
                }
            }
        }
    }

    //根据pag值转换成烈度
    private String sectionPag(Double value) {
        if (value < 0.04) {
            return "ld0";
        }
        if (0.04 <= value & value < 0.09) {
            return "ld1";
        }
        if (0.09 <= value & value < 0.19) {
            return "ld2";
        }
        if (0.19 <= value & value < 0.38) {
            return "ld3";
        }
        if (0.38 <= value & value < 0.75) {
            return "ld4";
        }
        if (0.75 <= value) {
            return "ld5";
        }
        return null;
    }

    private String sectionLD(String value) {
        if ("≤5".equals(value)) {
            return "ld0";
        }
        if ("6".equals(value)) {
            return "ld1";
        }
        if ("7".equals(value)) {
            return "ld2";
        }
        if ("8".equals(value)) {
            return "ld3";
        }
        if ("9".equals(value)) {
            return "ld4";
        }
        if ("10".equals(value)) {
            return "ld5";
        }
        if ("11".equals(value)) {
            return "ld6";
        }
        if ("12".equals(value)) {
            return "ld7";
        }
        return null;
    }

    /**
     * 存入数据,这十三个结构类型共同标记为字段geom;
     *
     * @param obj           数据obj
     * @param deQueryParam  条件obj
     * @param structureType 格网类型
     * @param result        计算值
     * @param totalArea     总面积
     * @return
     */
    private Calculation getCalculation(Grid13VO obj, DEQueryParam deQueryParam, String structureType, BigDecimal result, Double totalArea, String seismicInputMode) {
        Calculation calculation = new Calculation();
        //geom唯一坐标值
        calculation.setGeom(obj.getGeom());
        //省
        calculation.setProvince(obj.getProvince());
        //市
        calculation.setCity(obj.getCity());
        //县
        calculation.setCounty(obj.getCounty());
        //格网唯一id
        calculation.setExtends1(obj.getExtends1());
        //烈度
        if ("2".equals(seismicInputMode)) {
            calculation.setIntensity(obj.getIntensity());
        } else {
            calculation.setIntensity(deQueryParam.getCondition());
        }
        //记录一些结构类型
        calculation.setType(structureType);
        //计算出来的值
        calculation.setValue(result);
        //当前结构类型总面积
        calculation.setArea(BigDecimal.valueOf(totalArea));
        return calculation;
    }

    /**
     * 单体数据封装
     *
     * @param obj              数据obj
     * @param param            条件obj
     * @param tasks            任务obj
     * @param seismicInputMode 地震输入方式 0 烈度 1 4个概率 2 地震影响场
     * @param value            计算值
     * @return
     */
    private ResistEarthquakesCalculation getMonomerObj(BuildingIndividualEntity obj, DEQueryParam param, CalculationTasks tasks, String seismicInputMode, BigDecimal value, String condition) {
        ResistEarthquakesCalculation calculation = new ResistEarthquakesCalculation();
        //主键id
        calculation.setId(UUIDGenerator.getUUID());
        calculation.setCreateUser(PlatformSessionContext.getUserID());
        calculation.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        calculation.setDelFlag(YNEnum.N.toString());
        //地理id(虚拟ID) 或 房屋单体数据ID
        calculation.setGeographyId(obj.getBuildingCode());
        //省
        calculation.setProvinceName(obj.getProvince());
        //市
        calculation.setCityName(obj.getCity());
        //县
        calculation.setCountyName(obj.getCounty());
        //总面积
        calculation.setArea(BigDecimal.valueOf(Double.parseDouble(obj.getArea())));
        calculation.setExtends1(obj.getId());
        //calculation.setExtends1(String.valueOf(obj.getLongitude()) + String.valueOf(obj.getLatitude()));
        //条件
        calculation.setCondition(param.getCondition());
        //破坏状态
        calculation.setDamageDegree(param.getDamageDegree());

        if (seismicInputMode.equals("2")) {
            //写入影响场id
            calculation.setVersion(obj.getDzId());
            //影响场烈度
            calculation.setIntensity(obj.getDzIntensity());
        } else if (seismicInputMode.equals("1")) {
            //四个概率的烈度
            calculation.setIntensity(condition);
        } else {
            //烈度的烈度
            calculation.setIntensity(param.getCondition());
        }
        //计算值
        calculation.setCalculatedValue(value);
        //经验评估与修正值
        calculation.setCorrectionValue(value);
        //评估记录id
        calculation.setAssessId(tasks.getId());
        //评估记录code
        calculation.setAssessCode(tasks.getAssessCode());
        return calculation;
    }

    //获取到所有结构的值之后计算  (∑_i▒〖Area_i F_A^(S-IM) 〗)/Area
    //(∑_i▒〖Area_i F_A^(S-IM) 〗)为所有(结构类型根据设防情况乘以对应的易损性值)的和  ,  Area为所有结构类型的总面积
    private List<ResistEarthquakesCalculation> getConditionValue(DEQueryParam param, List<Calculation> list, CalculationTasks tasks, String seismicInputMode) {
        List<List<Calculation>> result = new ArrayList<>();
        Map<String, List<Calculation>> map = new HashMap<>();
        //将获得的所有数据进行归并,从而获得每个一样的geom下的所有计算值,并进行计算
        for (Calculation calculation : list) {
            String extends1 = calculation.getExtends1();
            List<Calculation> newList;
            if (map.containsKey(extends1)) {
                newList = map.get(extends1);
            } else {
                newList = new ArrayList<>();
            }
            newList.add(calculation);
            map.put(extends1, newList);
        }
        //写入list计算用
        for (Map.Entry<String, List<Calculation>> entry : map.entrySet()) {
            String key = entry.getKey();
            List<Calculation> calculations = map.get(key);
            result.add(entry.getValue());
        }
        //房屋抗震能力最终结果
        List<ResistEarthquakesCalculation> objectList = new ArrayList<>();
        for (List<Calculation> calculations : result) {

            ResistEarthquakesCalculation obj = new ResistEarthquakesCalculation();
            //区域内房屋总面积
            BigDecimal Area = BigDecimal.ZERO;
            //所有结构类型的值
            BigDecimal Areai = BigDecimal.ZERO;
            for (Calculation calculation : calculations) {
                //计算所有结构类型总面积
                Area = Area.add(calculation.getArea());
                //计算所有所有结构类型的值
                Areai = Areai.add(calculation.getValue());
            }
            BigDecimal value = BigDecimal.ZERO;
            if (Area.compareTo(BigDecimal.ZERO)>0) {
                value = Areai.divide(Area, 8, BigDecimal.ROUND_DOWN);
            }else{
                value = BigDecimal.valueOf(9999.9999);
            }
            //主键id
            obj.setId(UUIDGenerator.getUUID());
            //计算值
            obj.setCalculatedValue(value);
            //任务id
            obj.setAssessId(tasks.getId());
            //任务code
            obj.setAssessCode(tasks.getAssessCode());
            obj.setDamageDegree(param.getDamageDegree());
            obj.setCondition(param.getCondition());
            if (seismicInputMode.equals("2")) {
                //写入影响场版本
                obj.setVersion(tasks.getInfluenceFieldVersion());
            }
            //经验评估与修正值
            obj.setCorrectionValue(value);
            obj.setCreateUser(PlatformSessionContext.getUserID());
            obj.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            obj.setDelFlag(YNEnum.N.toString());
            //省
            obj.setProvinceName(calculations.get(0).getProvince());
            //市
            obj.setCityName(calculations.get(0).getCity());
            //县
            obj.setCountyName(calculations.get(0).getCounty());
            //空间数据
            obj.setGeom(calculations.get(0).getGeom());
            //格网唯一id
            obj.setExtends1(calculations.get(0).getExtends1());
            //格网虚拟id
            obj.setGeographyId(calculations.get(0).getExtends1());
            //烈度
            obj.setIntensity(calculations.get(0).getIntensity());
            //总面积
            obj.setArea(Area);
            objectList.add(obj);
        }
        return objectList;
    }

    /**
     * 计算面积
     *
     * @param v1 设防烈度占比
     * @param v2 总面积
     * @param v3 易损性值
     * @return
     */
    private BigDecimal getArea(Double v1, Double v2, Double v3) {
        //计算当前设防状态的面积
        //获取当前设防状态占比
        BigDecimal bigDecimal = BigDecimal.valueOf(v1).divide(BigDecimal.valueOf(100)).setScale(8, BigDecimal.ROUND_DOWN);
        //根据当前占比计算面积
        BigDecimal bigDecimal1 = bigDecimal.multiply(BigDecimal.valueOf(v2)).setScale(8, BigDecimal.ROUND_DOWN);
        BigDecimal bigDecimal3 = BigDecimal.ZERO;
        if (PlatformObjectUtils.isNotEmpty(v3)) {
            bigDecimal3 = BigDecimal.valueOf(v3).divide(BigDecimal.valueOf(100)).setScale(8, BigDecimal.ROUND_DOWN);
        }
        //根据易损性值计算最终结果
        BigDecimal bigDecimal2 = bigDecimal1.multiply(bigDecimal3).setScale(8, BigDecimal.ROUND_DOWN);
        return bigDecimal2;
    }

    //易损性获取
    //根据烈度值获取易损性這
    private Double getYSXValueByCondition(String condition, YSXEntity ysxEntity) {
        if (condition.equals("ld1")) {
            return ysxEntity.getIntensity6();
        }
        if (condition.equals("ld2")) {
            return ysxEntity.getIntensity7();
        }
        if (condition.equals("ld3")) {
            return ysxEntity.getIntensity8();
        }
        if (condition.equals("ld4")) {
            return ysxEntity.getIntensity9();
        }
        if (condition.equals("ld5")) {
            return ysxEntity.getIntensity10();
        }
        return null;
    }

    //导入计算
    @Override
    public String reportImport(InputStream inputStream, String type, String id, String code) {
        Workbook workbook = null;
        try {
            workbook = WorkbookFactory.create(inputStream);

            Map<String, Object> map = getList(workbook, type, id, code);
            Object o = map.get("message");
            if (o != null) {
                return String.valueOf(o);
            } else {
                List<ResistEarthquakesCalculation> list = (List<ResistEarthquakesCalculation>) map.get("list");
                resistEarthquakesDERepository.batchCalculation(list);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "成功";
    }

    //导出计算导数据
    @Override
    public void exportData(HttpServletResponse response, ResistEarthquakesCalculationParam param) {
        //条件(地震烈度 或 四个概率水准)
        if (param.getSeismicInputMode().equals("0")) {
            ExcelUtil.setExcelAnnotationValue(ResistEarthquakesPCCVO.class, "condition",
                    "name", "烈度");
        }
        if (param.getSeismicInputMode().equals("1")) {
            ExcelUtil.setExcelAnnotationValue(ResistEarthquakesPCCVO.class, "condition",
                    "name", "四个概率");
        }
        if (param.getSeismicInputMode().equals("2")) {
            CalculationTasks byId = calculationTasksRepository.findById(param.getId());
            param.setCondition(byId.getInfluenceFieldVersion());
            //地震影响场没有条件字段
            ArrayList<String> list = new ArrayList<>();
            list.add("condition");
            ExcelUtil.hideColumn(ResistEarthquakesPCCVO.class, list, true);
        }
        List<ResistEarthquakesPCCVO> list = resistEarthquakesDERepository.getListPCC(param);
        try {
            EasyPoiExcelUtil.exportExcel(list, "计算值", "计算值", ResistEarthquakesPCCVO.class, "抗震能力确定评估计算.xlsx", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据条件查询计算值
     *
     * @param seismicInputMode 震输入方式0烈度,1四个概率水准,2地震影响场
     * @param id               评估记录id
     * @param condition        条件(地震烈度 或 四个概率水准)
     * @param damageDegree     破坏程度
     * @return
     */
    @Override
    public Map<String, Object> queryCalculation(int curPage, int pageSize, String seismicInputMode, String id, String
            condition, String damageDegree) {
        Map<String, Object> page = resistEarthquakesDERepository.queryCalculation(seismicInputMode, curPage, pageSize, id, condition, damageDegree);
        return page;
    }

    //获取list
    private Map<String, Object> getList(Workbook workbook, String type, String id, String code) throws
            UnsupportedEncodingException {
        String userID = PlatformSessionContext.getUserID();
        Map<String, Object> map = new HashMap<>();
        List<ResistEarthquakesCalculation> list = new ArrayList<>();
        Boolean mark = true;
        if (Integer.parseInt(type) > 2) {
            mark = false;
        }
        if (workbook != null) {
            //循环除了第一行的所有行
            /** 得到第一个sheet */
            Sheet sheet = workbook.getSheetAt(0);
            /** 得到Excel的行数 */
            int totalRows = sheet.getPhysicalNumberOfRows();
            HSSFDataFormatter hSSFDataFormatter = new HSSFDataFormatter();
            /** 循环Excel的行 从第七行开始*/
            for (int r = 3; r < totalRows; r++) {
                Row row = sheet.getRow(r);
                if (row == null) {
                    continue;
                }
                ResistEarthquakesCalculation obj = new ResistEarthquakesCalculation();
                if (mark) {
                    //按照省市县输入时校验
                    Map<String, Object> check = check(row, type);
                    //如果没有message
                    if (check.get("message") == null) {
                        //省
                        obj.setProvinceName(hSSFDataFormatter.formatCellValue(row.getCell(0)));
                        //市
                        obj.setCityName(hSSFDataFormatter.formatCellValue(row.getCell(1)));
                        //县
                        obj.setCountyName(hSSFDataFormatter.formatCellValue(row.getCell(2)));
                        //建筑物公里网格ID（建筑物单体ID）
                        obj.setGeographyId(hSSFDataFormatter.formatCellValue(row.getCell(3)));
                        //条件(地震烈度 或 四个概率水准)
                        if (type.equals("1")) {
                            obj.setCondition(dictService.getKeyByDictCodeAndValue("ld", hSSFDataFormatter.formatCellValue(row.getCell(4))));
                        } else {
                            obj.setCondition(dictService.getKeyByDictCodeAndValue("sgglsz", hSSFDataFormatter.formatCellValue(row.getCell(4))));
                        }
                        //破坏程度
                        obj.setDamageDegree(dictService.getKeyByDictCodeAndValue("pgcd", hSSFDataFormatter.formatCellValue(row.getCell(5))));
                        //计算值
                        BigDecimal calculatedValue = new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(6)));
                        obj.setCalculatedValue(calculatedValue);
                        //经验评估与修正值
                        obj.setCorrectionValue(calculatedValue);
                    } else {
                        return check;
                    }
                } else {
                    //按照坐标范围输入时校验
                    Map<String, Object> check = check2(row, type);
                    //如果没有message
                    if (check.get("message") == null) {
                        //经纬度坐标范围
                        obj.setCoordinateRange(hSSFDataFormatter.formatCellValue(row.getCell(0)));
                        //建筑物公里网格ID（建筑物单体ID）
                        obj.setGeographyId(hSSFDataFormatter.formatCellValue(row.getCell(1)));
                        //条件(地震烈度 或 四个概率水准)
                        if (type.equals("2")) {
                            obj.setCondition(dictService.getKeyByDictCodeAndValue("ld", hSSFDataFormatter.formatCellValue(row.getCell(2))));
                        } else {
                            obj.setCondition(dictService.getKeyByDictCodeAndValue("sgglsz", hSSFDataFormatter.formatCellValue(row.getCell(2))));
                        }
                        //破坏程度
                        obj.setDamageDegree(dictService.getKeyByDictCodeAndValue("pgcd", hSSFDataFormatter.formatCellValue(row.getCell(3))));
                        //计算值
                        BigDecimal calculatedValue = new BigDecimal(hSSFDataFormatter.formatCellValue(row.getCell(4)));
                        obj.setCalculatedValue(calculatedValue);
                        //经验评估与修正值
                        obj.setCorrectionValue(calculatedValue);
                    } else {
                        return check;
                    }
                }
                //评估记录id
                obj.setAssessId(id);
                //评估记录code
                obj.setAssessCode(code);
                //主键id
                obj.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                //创建人
                obj.setCreateUser(userID);
                //创建时间
                obj.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
                list.add(obj);
            }
        }
        map.put("list", list);
        return map;
    }

    //数据校验省市县
    private Map<String, Object> check(Row row, String type) throws UnsupportedEncodingException {
        HashMap<String, Object> map = new HashMap<>();
        HSSFDataFormatter hSSFDataFormatter = new HSSFDataFormatter();
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(0)))) {
            map.put("message", "省不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(1)))) {
            map.put("message", "市不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(2)))) {
            map.put("message", "县不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(3)))) {
            map.put("message", "建筑物公里网格ID（建筑物单体ID）不能为空");
        }
        if (type.equals("1")) {
            if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(4)))) {
                map.put("message", "烈度不能为空");
            }
        } else {
            if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(4)))) {
                map.put("message", "四个概率水准不能为空");
            }
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(5)))) {
            map.put("message", "破坏程度不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(6)))) {
            map.put("message", "计算值不能为空");
        }
        String province = hSSFDataFormatter.formatCellValue(row.getCell(0));
        String city = hSSFDataFormatter.formatCellValue(row.getCell(1));
        String county = hSSFDataFormatter.formatCellValue(row.getCell(2));
        // 根据省市县名称获得省市县id _ 分割
        String divisionIds = sysAreaService.getIdByCondition(
                URLEncoder.encode(province, "UTF-8"),
                URLEncoder.encode(city, "UTF-8"),
                URLEncoder.encode(county, "UTF-8"));
        if (divisionIds == null) {
            map.put("message", "省市县错误" + province + "_" + city + "_" + county);
        }
        String[] s = divisionIds.split("_");
        if (s.length != 3) {
            map.put("message", "省市县错误" + province + "_" + city + "_" + county);
        }
        return map;
    }

    //范围校验
    private Map<String, Object> check2(Row row, String type) throws UnsupportedEncodingException {
        HashMap<String, Object> map = new HashMap<>();
        HSSFDataFormatter hSSFDataFormatter = new HSSFDataFormatter();
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(0)))) {
            map.put("message", "坐标范围不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(1)))) {
            map.put("message", "建筑物公里网格ID（建筑物单体ID）不能为空");
        }
        if (type.equals("1")) {
            if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(2)))) {
                map.put("message", "烈度不能为空");
            }
        } else {
            if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(2)))) {
                map.put("message", "四个概率水准不能为空");
            }
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(3)))) {
            map.put("message", "破坏程度不能为空");
        }
        if (StringUtils.isEmpty(hSSFDataFormatter.formatCellValue(row.getCell(4)))) {
            map.put("message", "计算值不能为空");
        }
        return map;
    }

    /**
     * 确认评估风险区划-区划
     *
     * @param entity
     * @return
     */
    @Override
    public List<FxqhAssessEdQhResult> doZoning(FxqhAssessEdQh entity) throws UnsupportedEncodingException, BizException {
        List<FxqhAssessEdQhResult> resultList = new ArrayList<>();
        Map<String, String> areaIdCodeMap = (Map<String, String>) JSON.parse((String) redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaIdCodeMap"));
        String divisionNames = entity.getDivisionNames();
        String assessCodes = entity.getAssessCodes();
        String condition = entity.getCondition();
        for (String divisionName : divisionNames.split(",")) {
            String[] split = divisionName.split("-");
            /**获取所有省市县的易损性数据
             * Map<String, Map<String, List<BuildingVulnerability>>>:
             * key 是建筑物结构类型
             * value是相同结构类型的集合
             * Map<String, List<BuildingVulnerability>>:
             * key 是设防烈度
             * value是相同设防烈度的集合
             * List<BuildingVulnerability>:各个地震烈度的破坏程度数据
             * BuildingVulnerability:各个破坏程度的数据
             */
            // Map<String, Map<String, List<BuildingVulnerability>>> ysxData = tools.getYSX(split[0], split[1], split[2]);

            List<Map<String, Object>> list = resistEarthquakesDERepository.getSumByDivisionAndAssessCodes(split[0], split[1], split[2],
                    assessCodes, condition, entity.getSeismicInputMode());
            // String extends1 = "";
            BigDecimal sumArea = BigDecimal.ZERO;
            BigDecimal calculatedValue = BigDecimal.ZERO;
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map = list.get(i);
                if (i == 0 && ((Long) map.get("count")) > 1) {
                    throw new RuntimeException("所选评估记录中有重复区县，请重新选择！");
                }
                String damageDegree = (String) map.get("damageDegree");
                BigDecimal area = BigDecimal.valueOf((Double) map.get("area"));
                switch (damageDegree) {
                    case "pgcd4":
                    case "pgcd5":
                        calculatedValue = calculatedValue.add(BigDecimal.valueOf((Double) map.get("sum")).multiply(area));
                        break;
                }
                sumArea = sumArea.add(area);
                // if (!extends1.equals((String) map.get("extends1"))) {
                //     calculatedValue = BigDecimal.ZERO;
                // }
                // extends1 = (String) map.get("extends1");
                // calculatedValue=calculatedValue.add(BigDecimal.valueOf((Double)map.get("sum")));
            }
            String divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(split[0], "UTF-8"),
                    URLEncoder.encode(split[1], "UTF-8"), URLEncoder.encode(split[2], "UTF-8"));
            String code = null;
            if (areaIdCodeMap==null||areaIdCodeMap.size()<1) {
                code = sysAreaService.getDivisionCodeById(divisionIds.split("_")[2]);
            }else {
                code = areaIdCodeMap.get(divisionIds.split("_")[2]);
            }
            String geom = jcsjRestManager.getGeomByCode(code,"3");
            if (geom == null) {
                throw new RuntimeException("未获取到" + split[0] + split[1] + split[2] + "的空间数据！");
            }

            FxqhAssessEdQhResult result = new FxqhAssessEdQhResult();
            result.setProvince(split[0]);
            result.setCity(split[1]);
            result.setCounty(split[2]);
            if ("新疆维吾尔自治区".equals(split[0]) || "青海省".equals(split[0]) || "西藏自治区".equals(split[0])) {
                result.setBorderlandFlag("1");
            } else {
                result.setBorderlandFlag("0");
            }
            if (list.size() > 0) {
                result.setCalculatedValue(calculatedValue.divide(sumArea, 8, BigDecimal.ROUND_UP));
            }
            result.setEstimateObj("1");
            // result.setCalculatedValue(calculatedValue.divide(sumArea, 8, BigDecimal.ROUND_UP));
            result.setGeom(geom);
            resultList.add(result);
        }
        return resultList;
    }

    @Override
    public List<FxqhAssessEdQhResult> doZoning(CalculationTasks task) throws UnsupportedEncodingException, BizException {
        List<FxqhAssessEdQhResult> resultList = new ArrayList<>();
        Map<String, String> areaIdCodeMap = (Map<String, String>) JSON.parse((String) redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaIdCodeMap"));
        List<PCC> pccList = null;
//        if (task.getRadio2().equals("0")) {
        pccList = task.getList();
//        } else {
//            pccList = pccRepository.queryToponym(task.getId());
//        }
        for (PCC pcc : pccList) {
            String divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(pcc.getPpName(), "UTF-8"),
                    URLEncoder.encode(pcc.getCityName(), "UTF-8"), URLEncoder.encode(pcc.getName(), "UTF-8"));
            String code = null;
            if (areaIdCodeMap==null||areaIdCodeMap.size()<1) {
                code = sysAreaService.getDivisionCodeById(divisionIds.split("_")[2]);
            }else {
                code = areaIdCodeMap.get(divisionIds.split("_")[2]);
            }
            String geom = jcsjRestManager.getGeomByCode(code,"3");
            if (geom == null) {
                // throw new RuntimeException("未获取到" + pcc.getPpName() + pcc.getCityName() + pcc.getName() + "的空间数据！");
                continue;
            }
            String[] conditionArr = new String[]{};
            // 0、烈度；1、4个概率水准；2、地震影响场
            for (String seiMode : task.getSeismicInputMode().split(",")) {
                if (seiMode.equals("0")) {
                    conditionArr = new String[]{"ld1", "ld2", "ld3", "ld4", "ld5"};
                } else if (seiMode.equals("1")) {
                    conditionArr = new String[]{"sgglsz1", "sgglsz2", "sgglsz3", "sgglsz4"};
                } else {
                    conditionArr = new String[]{task.getInfluenceFieldVersion()};
                }
                for (String condition : conditionArr) {
                    /**获取所有省市县的易损性数据
                     * Map<String, Map<String, List<BuildingVulnerability>>>:
                     * key 是建筑物结构类型
                     * value是相同结构类型的集合
                     * Map<String, List<BuildingVulnerability>>:
                     * key 是设防烈度
                     * value是相同设防烈度的集合
                     * List<BuildingVulnerability>:各个地震烈度的破坏程度数据
                     * BuildingVulnerability:各个破坏程度的数据
                     */
                    // Map<String, Map<String, List<BuildingVulnerability>>> ysxData = tools.getYSX(pcc.getPpName(), pcc.getCityName(), pcc.getName());

                    List<Map<String, Object>> list = resistEarthquakesDERepository.getSumByDivisionAndAssessCodes(pcc.getPpName(), pcc.getCityName(), pcc.getName(),
                            task.getId(), condition, seiMode);
                    // String extends1 = "";
                    BigDecimal sumArea = BigDecimal.ZERO;
                    BigDecimal calculatedValue = BigDecimal.ZERO;
                    for (int i = 0; i < list.size(); i++) {
                        Map<String, Object> map = list.get(i);
                        String damageDegree = (String) map.get("damageDegree");
                        BigDecimal area = (BigDecimal) map.get("area");
                        switch (damageDegree) {
                            case "pgcd4":
                            case "pgcd5":
                                calculatedValue = calculatedValue.add(BigDecimal.valueOf((Double) map.get("sum")).multiply(area));
                                break;
                        }
                        sumArea = sumArea.add(area);
                        // if (!extends1.equals((String) map.get("extends1"))) {
                        //     calculatedValue = BigDecimal.ZERO;
                        // }
                        // extends1 = (String) map.get("extends1");
                        // calculatedValue=calculatedValue.add(BigDecimal.valueOf((Double)map.get("sum")));
                    }

                    FxqhAssessEdQhResult result = new FxqhAssessEdQhResult();
                    result.setProvince(pcc.getPpName());
                    result.setCity(pcc.getCityName());
                    result.setCounty(pcc.getName());
                    if ("新疆维吾尔自治区".equals(pcc.getPpName()) || "青海省".equals(pcc.getPpName()) || "西藏自治区".equals(pcc.getPpName())) {
                        result.setBorderlandFlag("1");
                    } else {
                        result.setBorderlandFlag("0");
                    }
                    if (list.size() > 0) {
                        if (calculatedValue.equals(BigDecimal.ZERO)) {
                            result.setCalculatedValue(BigDecimal.ZERO);
                        } else {
                            result.setCalculatedValue(calculatedValue.divide(sumArea, 8, BigDecimal.ROUND_UP));
                        }
                    } else {
                        result.setCalculatedValue(BigDecimal.ZERO);
                    }
                    result.setGeom(geom);
                    result.setId(UUIDGenerator.getUUID());
                    result.setTaskId(task.getId());
                    result.setEstimateObj("0");
                    result.setHouseDataFlag(task.getHouseDataFlag());
                    result.setCondition(condition);
                    result.setSeismicInputMode(getSeismicInputModeByCondition(condition));
                    resultList.add(result);
                }
            }
        }
        return resultList;
    }

    public static String getSeismicInputModeByCondition(String condition) {
        String[] ld = {"ld1", "ld2", "ld3", "ld4", "ld5"};
        String[] sdld = new String[]{"sgglsz1", "sgglsz2", "sgglsz3", "sgglsz4"};
        if (Arrays.asList(ld).contains(condition)) {
            return "0";
        } else if (Arrays.asList(sdld).contains(sdld)) {
            return "1";
        } else {
            return "2";
        }
    }
}

